package commConfig

import (
	"encoding/json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisStatus"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
)

type InitialConfigService struct {
	defaultConfigs map[string]interface{} // 缺省配置
}

func (e *InitialConfigService) Initialize(configName string, jsn string) error {
	if e.defaultConfigs == nil {
		e.defaultConfigs = make(map[string]interface{})
	}

	// 获得缺省值
	defaultConfig := e.defaultConfigs[configName]
	if defaultConfig == nil {
		var vo map[string]interface{}
		err := json.Unmarshal([]byte(jsn), &vo)
		if err != nil {
			return err
		}

		defaultConfig = vo
		e.defaultConfigs[configName] = defaultConfig
	}

	//interface{}转换位map
	ptrConfig := defaultConfig.(map[string]interface{})

	// 填写该信息：通知管理服务，添加该配置作为缺省配置
	e.notifyRegisterConfig(configName, ptrConfig)

	return nil
}

func (e *InitialConfigService) GetConfigParam(configName string) (map[string]interface{}, error) {
	// 取出数据
	defaultConfig := Map.GetOrDefault(e.defaultConfigs, configName, make(map[string]interface{}))
	out := defaultConfig.(map[string]interface{})

	// 取出数据
	result := make(map[string]interface{})
	configValue := Map.GetOrDefault(out, "configValue", make(map[string]interface{}))
	out = configValue.(map[string]interface{})

	// 将数据添加到result
	Map.Append(result, out)

	configEntity := commRedisService.GetConfigEntity(commEnv.Service.ServiceName, commEnv.Service.ServiceType, configName)
	if configEntity == nil {
		return result, nil
	}

	Map.Append(result, configEntity.ConfigValue)

	return result, nil
}

func (e *InitialConfigService) notifyRegisterConfig(configName string, config map[string]interface{}) {
	configEntity := commRedisStatus.Producer.GetValue("configEntity")
	if configEntity == nil {
		configEntity = make(map[string]interface{})
		commRedisStatus.Producer.SetValue("configEntity", configEntity)
	}

	configItem := configEntity.(map[string]interface{})[configName]
	if configItem == nil {
		configItem = make(map[string]interface{})
		configEntity.(map[string]interface{})[configName] = configItem
	}

	Map.Append(configItem.(map[string]interface{}), config)
	commRedisStatus.Producer.SetValue("configEntity", configEntity)
}
